package com.zlz.server.tasks;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zlz.server.constant.MailConstant;
import com.zlz.server.pojo.Employee;
import com.zlz.server.pojo.MailLog;
import com.zlz.server.service.IEmployeeService;
import com.zlz.server.service.IMailLogService;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author: zlz
 * @date: 2021/3/19 11:18
 * @description: 邮件定时任务
 * @since: JDK1.8
 */
@Component
public class MailTask {
    @Resource
    private IMailLogService iMailLogService;

    @Resource
    private IEmployeeService iEmployeeService;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Scheduled(cron = "0/10 * * * * ?")
    public void mailTask() {
        List<MailLog> mailLogs = iMailLogService.list(new QueryWrapper<MailLog>().eq("status", 0)
                .lt("try_time", LocalDateTime.now()));
        mailLogs.forEach(mailLog -> {
            // 如果重试次数超过3次，更新状态为投递失败，不再重试
            if (mailLog.getCount() >= MailConstant.MAX_TRY_COUNT) {
                iMailLogService.update(new UpdateWrapper<MailLog>().set("status", MailConstant.DELIVER_FAILED)
                        .eq("msg_id", mailLog.getMsgId()));
            }
            iMailLogService.update(new UpdateWrapper<MailLog>().set("count", mailLog.getCount() + 1)
                    .set("update_time", LocalDateTime.now())
                    .set("try_time", LocalDateTime.now().plusMinutes(MailConstant.MSG_TIMEOUT))
                    .eq("msg_id", mailLog.getMsgId()));

            Employee employee = iEmployeeService.getEmployee(mailLog.getEid()).get(0);
            // 发送消息
            rabbitTemplate.convertAndSend(MailConstant.MAIL_EXCHANGE_NAME, MailConstant.MAIL_ROUTING_KEY_NAME, employee,
                    new CorrelationData(mailLog.getMsgId()));
        });
    }
}
